package string;

/**
 * @Author: 海琳琦
 * @Date: 2022/2/1 13:38
 */
public class ReverseStr {

    public static String reverseStr(String s, int k) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < s.length(); ) {
            //剩余的字符串小于k
            if (s.length() - 1 - i < k) {
                result.append(new StringBuffer(s.substring(i, s.length())).reverse());
                return result.toString();
            }
            //如果剩余字符小于 2k 但大于或等于 k 个，则反转前 k 个字符，其余字符保持原样。
            String substring = s.substring(i, i + k);
            result.append(new StringBuilder(substring).reverse());
            if (s.length() - 1 - i < 2 * k) {
                result.append(s, i + k, s.length());
            } else {
                result.append(s, i + k, i + 2 * k );
            }
            i += 2 * k;
        }
        return result.toString();
    }

    public static void main(String[] args) {
        System.out.println(reverseStr("abcdefg",1));
    }
}
